/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.d.ui.view.lrc;


import com.d.lib.common.widget.TitleLayout;
import com.d.lib.ui.view.LogUtil;
import com.d.lib.ui.view.lrc.DefaultLrcParser;
import com.d.lib.ui.view.lrc.LrcRow;
import com.d.lib.ui.view.lrc.LrcView;
import com.d.ui.view.ResourceTable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Slider;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.RawFileDescriptor;
import ohos.media.common.Source;
import ohos.media.player.Player;
import static ohos.data.search.schema.PhotoItem.TAG;

public class LrcViewAbility extends AbilitySlice implements Player.IPlayerCallback,
    Slider.ValueChangedListener, Component.ClickedListener {

  private LrcView lrcv_lrc;
  private Slider sb_progress;
  private Slider sb_scale;
  private Text tv_play_pause;
  private Player mPlayer;
  private boolean mIsPressed;
  Image image;
  private boolean mIsRunning;
  private EventHandler mHandler = new EventHandler(EventRunner.create());


  private Runnable mRunnable = new Runnable() {

    @Override
    public void run() {
      if (!mIsRunning) {
        return;
      }
      setProgress();
      mHandler.postTask(mRunnable, 500);
    }
  };


  private void setProgress() {
    if (!mIsPressed) {
      getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
        @Override
        public void run() {
          sb_progress.setMaxValue(mPlayer.getDuration());
          sb_progress.setProgressValue(mPlayer.getCurrentTime());
        }
      });
    }
  }

  @Override
  public void onStart(Intent intent) {
    super.onStart(intent);
    super.setUIContent(ResourceTable.Layout_ability_lrc);
    bindView();
    initListener();
  }

  private void bindView() {
    lrcv_lrc = (LrcView) findComponentById(ResourceTable.Id_lrcv_lrc);
    sb_progress = (Slider) findComponentById(ResourceTable.Id_sb_progress);
    sb_scale = (Slider) findComponentById(ResourceTable.Id_sb_scale);
    ShapeElement shapeElement = new ShapeElement();
    shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#108577")));
    shapeElement.setBounds(0, 0, 40, 40);
    shapeElement.setCornerRadius(40);
    sb_progress.setThumbElement(shapeElement);
    sb_scale.setThumbElement(shapeElement);
    tv_play_pause = (Text) findComponentById(ResourceTable.Id_tv_play_pause);
    tv_play_pause.setClickedListener(this::onClick);
    TitleLayout titleLayout = (TitleLayout) findComponentById(ResourceTable.Id_tl_title);
    titleLayout.setBackClickListener(new Component.ClickedListener() {
      @Override
      public void onClick(Component component) {
        terminate();
      }
    });
  }

  private void initListener() {
    sb_progress.setValueChangedListener(this);
    sb_scale.setValueChangedListener(this);
    sb_scale.setMaxValue(100);
    sb_scale.setProgressValue(50);
    initPlayer();
    initLrc();
  }

  private void initPlayer() {
    RawFileDescriptor filDescriptor = null;
    try {
      filDescriptor =
          getResourceManager().getRawFileEntry("resources/rawfile/huasha.mp3").openRawFileDescriptor();
    } catch (IOException e) {
      e.printStackTrace();
    }
    Source source = new Source(filDescriptor.getFileDescriptor(),
        filDescriptor.getStartPosition(), filDescriptor.getFileSize());
    mPlayer = new Player(getContext());
    mPlayer.setSource(source);
    mPlayer.prepare();
    mPlayer.setPlayerCallback(this);
  }

  private void initLrc() {
    lrcv_lrc.setOnSeekChangeListener(new LrcView.OnSeekChangeListener() {
      @Override
      public void onProgressChanged(int progress) {
        mPlayer.rewindTo(progress * 1000);
        setProgress();

      }
    });
    lrcv_lrc.setOnClickListener(new LrcView.OnClickListener() {
      @Override
      public void onClick() {
        LogUtil.debug(TAG, "Click lrc! ");
      }
    });
  }

  @Override
  public void onActive() {
    super.onActive();
  }

  @Override
  public void onForeground(Intent intent) {
    super.onForeground(intent);
  }

  @Override
  public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {
    if (slider == sb_progress) {
      lrcv_lrc.seekTo(progress, fromUser);
    } else if (slider == sb_scale && fromUser) {
      lrcv_lrc.setLrcScale(progress / 100f);
    }
  }

  @Override
  public void onTouchStart(Slider slider) {
    if (slider == sb_progress) {
      mIsPressed = true;
    }
  }

  @Override
  public void onTouchEnd(Slider slider) {
    if (slider == sb_progress) {
      mIsPressed = false;
      mPlayer.rewindTo(slider.getProgress() * 1000);
    }
  }

  @Override
  public void onClick(Component component) {
    int resId = component.getId();
    if (ResourceTable.Id_tv_play_pause == resId) {
      if ("Play".equals(tv_play_pause.getText())) {
        mPlayer.play();
        lrcv_lrc.setLrcRows(getLrcRows());
        tv_play_pause.setText("暂停");
        reStartTimer();
      } else {
        if (mPlayer.isNowPlaying()) {
          mPlayer.pause();
          tv_play_pause.setText("播放");
          stopTimer();
        } else {
          mPlayer.play();
          tv_play_pause.setText("暂停");
          reStartTimer();
        }
      }
    }
  }

  private List<LrcRow> getLrcRows() {
    List<LrcRow> rows = null;
    String filePath = String.format("assets/entry/resources/rawfile/%s", "huashalrc.lrc");

    InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
    LogUtil.debug(TAG, "is: " + is);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuilder sb = new StringBuilder();
    try {
      while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
      }
      rows = DefaultLrcParser.getLrcRows(sb.toString());
    } catch (Throwable e) {
      e.printStackTrace();
    }
    return rows;
  }

  private void reStartTimer() {
    stopTimer();
    mIsRunning = true;
    mHandler.postTask(mRunnable);
  }

  private void stopTimer() {
    mIsRunning = false;
    mHandler.removeTask(mRunnable);
  }

  @Override
  protected void onStop() {
    stopTimer();
    if (mPlayer != null) {
      mPlayer.stop();
      mPlayer.release();
      mPlayer = null;
    }
    if (lrcv_lrc != null) {
      lrcv_lrc.reset();
    }
    super.onStop();
  }

  @Override
  public void onPrepared() {

  }

  @Override
  public void onMessage(int i, int i1) {

  }

  @Override
  public void onError(int i, int i1) {

  }

  @Override
  public void onResolutionChanged(int i, int i1) {

  }

  @Override
  public void onPlayBackComplete() {
    stopTimer();
    mPlayer.rewindTo(0);
    sb_progress.setProgressValue(0);
  }

  @Override
  public void onRewindToComplete() {

  }

  @Override
  public void onBufferingChange(int i) {

  }

  @Override
  public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {

  }

  @Override
  public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {

  }
}
